#pragma once

#include <iostream>
#include <queue>
#include <pthread.h>

template<class T>
class BlockQueue
{
    static const int cap = 10;

public:
    BlockQueue(int cap = cap)
    : _cap(cap)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_pcond, nullptr);
        pthread_cond_init(&_ccond, nullptr);
    }

    T Pop()
    {
        pthread_mutex_lock(&_mutex);

        while(_q.size() == 0)
        {
            pthread_cond_wait(&_ccond, &_mutex);
        }
        T t = _q.front();
        _q.pop();
        pthread_cond_signal(&_pcond);

        pthread_mutex_unlock(&_mutex);
        return t;
    }

    void Push(const T& t)
    {
        pthread_mutex_lock(&_mutex);

        while(_q.size() == _cap)
        {
            pthread_cond_wait(&_pcond, &_mutex);
        }
        _q.push(t);
        pthread_cond_signal(&_ccond);

        pthread_mutex_unlock(&_mutex);
    }

    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_ccond);
        pthread_cond_destroy(&_pcond);
    }

private:
    std::queue<T> _q;
    int _cap;
    pthread_mutex_t _mutex;
    pthread_cond_t _pcond;
    pthread_cond_t _ccond;
};